import { sm2 } from "sm-crypto-v2";
import { Buffer } from "buffer";

/**
 * SM2加密
 * @param data 待加密数据
 * @returns 加密结果
 */
export function encryptSM2(data: string): string {
  const publicKeyBase64 = import.meta.env.VITE_SM2_PUBLIC_KEY;
  if (!publicKeyBase64) {
    throw new Error("未设置环境变量 VITE_SM2_PUBLIC_KEY");
  }
  const publicKey = Buffer.from(publicKeyBase64, "base64").toString("hex");
  const result = sm2.doEncrypt(data, publicKey, 0);
  return Buffer.from(`04${result}`, "hex").toString("base64");
}
